var util = require('../../utils/util.js')
const db = wx.cloud.database()
const app = getApp();
Page({
  data: {
    news: {},
    comment: {},
    message: '',
    newsid: '',
    fill: false
  },

  onLoad: function(options) {
    const newsid = options.id
    db.collection('news').doc(newsid).get().then(res => {
      res.data.time = util.formatTime(res.data.submitdate)
      this.setData({
        newsid: newsid,
        news: res.data
      })
    })

    db.collection('newscomment').where({
      newsid: newsid
    }).orderBy('submitdate', 'desc').get().then(res => {
      for (var index in res.data)
        res.data[index].time = util.formatTime(res.data[index].submitdate)
      this.setData({
        comment: res.data
      })
    })

  },

  ViewImage(e) {
    wx.previewImage({
      urls: this.data.news.imgUrl,
      current: e.currentTarget.dataset.url
    });
  },

  InputFocus(e) {
    this.setData({
      InputBottom: e.detail.height
    })
  },
  
  InputBlur(e) {
    this.setData({
      InputBottom: 0
    })
  },

  inputcomment(event) {
    this.setData({
      message: event.detail.value
    })
  },

  appreciate: function(event) {
    console.log('fill')
    var fill = this.data.fill;
    var value = fill ? -1 : 1
    wx.cloud.callFunction({
      name: 'news',
      data: {
        $url: "appreciate_inc", // 要调用的路由的路径，传入准确路径或者通配符*
        id: this.data.newsid,
        value: value
      },
      success: res => {
        //console.log(res)
      }
    })
    this.setData({
      fill: !fill
    })
  },

  sendmessage(event) {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo == "") {
      wx.navigateTo({
        url: '../auth/auth'
      })
      return
    }
    var newsid = this.data.newsid
    db.collection('newscomment').add({
      data: {
        newsid: newsid,
        message: this.data.message,
        nickName: userInfo.nickName,
        gender: userInfo.gender,
        avatarUrl: userInfo.avatarUrl,
        submitdate: db.serverDate(),
      }
    }).then(res => {
      db.collection('newscomment').where({
        newsid: newsid
      }).orderBy('submitdate', 'desc').get().then(res => {
        for (var index in res.data)
          res.data[index].time = util.formatTime(res.data[index].submitdate)
        this.setData({
          comment: res.data, message:''
        })
      })
      wx.cloud.callFunction({
        name: 'news',
        data: {
          $url: "comment_inc", // 要调用的路由的路径
          id: newsid,
        },
        success: res => {
          console.log(res)
        }
      })
      wx.showToast({
        title: '评论成功...',
        icon: 'none',
        duration: 1500
      })
    })
  },
})